﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Resources;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace IntraVision.Web.Toolkit
{
    public static class HTMLHelper
    {
        public static string EscapeQuotes(string val)
        {
            if( string.IsNullOrEmpty(val) ) return val;
            return val.Replace("\"","&quot;");
        }

        public static string EscapeHTML(string val)
        {
            if (string.IsNullOrEmpty(val)) return val;
            return val.Replace("<", "&lt;").Replace(">", "&gt;");
        }

        public static string TextInput(string id, object value)
        {
            return Input("text", id, value, "", 0, false);
        }

        public static string TextInput(string id, object value, string classes, int maxlength)
        {
            return Input("text", id, value, classes, maxlength, false);
        }

        public static string TextInput(string id, object value, string classes, int maxlength,bool disabled)
        {
            return Input("text", id, value, classes, maxlength, disabled);
        }

        public static string HiddenInput(string id, object value, string classes)
        {
            return Input("hidden", id, value, classes, 0, false);
        }

        public static string HiddenInput(string id, object value)
        {
            return Input("hidden", id, value, null, 0, false);
        }

        public static string Input(string type, string id, object value, string classes, int maxlength, bool disabled)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<input id=\"").Append(id).Append("\" name=\"").Append(id).Append("\" type=\"").Append(type).Append("\"");
            if (maxlength > 0) sb.Append("maxlength=\"").Append(maxlength).Append("\"");
            if (!string.IsNullOrEmpty(Convert.ToString(value))) sb.Append(" value=\"").Append(Convert.ToString(value).Replace(@"""",@"&quot;")).Append("\"");
            if (!string.IsNullOrEmpty(classes)) sb.Append(" class=\"").Append(classes).Append("\"");
            if (disabled) sb.Append(" disabled=\"true\"");
            sb.Append("/>");
            return sb.ToString();
        }

        public static string TextArea(string id, object value, string classes)
        {
            return TextArea(id, value, classes, 0, 0);
        }

        public static string TextArea(string id, object value, string classes, int rows, int cols)
        {
            string str1 = (string.IsNullOrEmpty(classes)) ? "" : "class=\"" + classes + "\"";
            string str2 = (rows > 0) ? " rows=\"" + rows + "\"" : "";
            string str3 = (cols > 0) ? " cols=\"" + cols + "\"" : "";
            return String.Format("<textarea id=\"{0}\" name=\"{0}\" {1} {2} {3}>{4}</textarea>", id, str1, str2, str3, Convert.ToString(value));
        }

        public static string Select(string id, object dataSource, string textField, string valueField, object selectedValue, string classes)
        {
            return Select(id, dataSource, textField, valueField, selectedValue, classes, "", "", false, false);
        }

        public static string Select(string id, object dataSource, string textField, string valueField, object selectedValue, string classes, bool readOnly)
        {
            return Select(id, dataSource, textField, valueField, selectedValue, classes, "", "", readOnly, false);
        }

        public static string Select(string id, object dataSource, string textField, string valueField, object selectedValue, string classes, bool readOnly, bool disabled)
        {
            return Select(id, dataSource, textField, valueField, selectedValue, classes, "", "", readOnly, disabled);
        }

        public static string Select(string id, object dataSource, string textField, string valueField, object selectedValue, string classes, string firstText, string firstValue, bool readOnly )
        {
            return Select(id, dataSource, textField, valueField, selectedValue, classes, firstText, firstValue, readOnly, false);
        }

        public static string Select(string id, object dataSource, string textField, string valueField, object selectedValue, string classes, string firstText, string firstValue, bool readOnly, bool disabled)
        {
            return Select(id, dataSource, textField, valueField, selectedValue, classes, firstText, firstValue, readOnly, disabled, "");
        }

        public static string Select(string id, object dataSource, string textField, string valueField, object selectedValue, string classes, string firstText, string firstValue, bool readOnly, bool disabled, string addParams)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<select id=\"").Append(id).Append("\" name=\"").Append(id).Append("\"");
            if (!string.IsNullOrEmpty(classes)) sb.Append(" class=\"").Append(classes).Append("\"");
            if (!string.IsNullOrEmpty(addParams)) sb.Append(" ").Append(addParams);
            if (readOnly) sb.Append(" disabled=\"true\"");
            sb.Append(">");
            if (firstText != "NONE") sb.AppendFormat("<option value=\"{0}\">{1}</option>", firstValue, firstText);

            string str2 = "\t\t<option value=\"{0}\" {1}>{2}</option>" + Environment.NewLine;

            DataTable table = DataBinder.EvalDataSource(dataSource, textField, valueField);
            foreach (DataRow row in table.Rows)
            {
                string str3 = string.Empty;
                string str4 = row[1].ToString();
                string str5 = row[0].ToString();
                if ((selectedValue != null) && str5 == selectedValue.ToString())
                    str3 = " selected=\"true\" ";
                sb.AppendFormat(str2, str5, str3, str4);
            }
            sb.Append("</select>");
            if (readOnly && !disabled) sb.AppendFormat("<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />", id, selectedValue);
            return sb.ToString();
        }

        public static string MultipleSelect(string id, object dataSource, string textField, string valueField, int[] selectedValues, string classes, bool readOnly)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<select id=\"").Append(id).Append("\" name=\"").Append(id).Append("\"");
            sb.Append(" class=\"hidden ").Append(classes).Append("\"");
            if (readOnly) sb.Append(" disabled=\"true\"");
            sb.Append(" multiple=\"true\">");

            string str2 = "\t\t<option value=\"{0}\" {1}>{2}</option>" + Environment.NewLine;

            DataTable table = DataBinder.EvalDataSource(dataSource, textField, valueField);
            var strOptions = new List<string>();
            foreach (DataRow row in table.Rows)
            {
                string str3 = string.Empty;
                string str4 = row[1].ToString();
                string str5 = row[0].ToString();
                if (selectedValues != null)
                {
                    foreach (int obj in selectedValues)
                    {
                        if (str5 == obj.ToString())
                        {
                            strOptions.Add(str4);
                            str3 = " selected=\"true\" ";
                            break;
                        }
                    }
                }
                sb.AppendFormat(str2, str5, str3, str4);
            }
            sb.Append("</select>");

            if (classes.IndexOf("nolink") < 0)
            {
                string title = strOptions.Count > 0 ? string.Join(", ", strOptions.ToArray()) : HTMLHelper.Resource("Common", "Select", "Выбрать");
                if (table.Rows.Count > 0)
                {
                    if (readOnly)
                        sb.Insert(0, HTMLHelper.Resource("Common", "NotDefined", "Не заданы"));
                    else
                        sb.Insert(0, String.Format(@"<div class=""checklisttitle""><a href=""#"" title=""{0}"">{0}</a></div>", title));
                }
                else
                    sb.Insert(0, string.Format(@"<div class=""checklisttitle"">{0}</div>",HTMLHelper.Resource("Common","NotDefined","Не заданы")));
            }

            if (readOnly) sb.AppendFormat("<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />", id, string.Join(",", (from sv in selectedValues select sv.ToString()).ToArray()));
            return sb.ToString();
        }

        public static string Link(string href, string text)
        {
            return Link(href, text, null, null);
        }

        public static string Link(string href, string text, string classes)
        {
            return Link(href, text, classes, null);
        }

        public static string Link(string href, string text, string classes, string target)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<a href=\"" + href + "\"");
            if (!string.IsNullOrEmpty(target)) sb.Append(" target=\"").Append(target).Append("\"");
            if (!string.IsNullOrEmpty(classes)) sb.Append(" class=\"").Append(classes).Append("\"");
            sb.Append(">").Append(text).Append("</a>");
            return sb.ToString();
        }

        public static string Checkbox(string id, object value)
        {
            return Checkbox(id, value, null, false);
        }

        public static string Checkbox(string id, object value, string classes, bool selected)
        {
            return Checkbox(id, value, classes, selected, false);
        }

        public static string Checkbox(string id, object value, string classes, bool? selected)
        {
            return Checkbox(id, value, classes, selected ?? false, false);
        }

        public static string Checkbox(string id, object value, string classes, bool selected, bool multiple)
        {
            return Checkbox(id, value, classes, selected, multiple, null);
        }

        public static string Checkbox(string id, object value, string classes, bool? selected, bool multiple)
        {
            return Checkbox(id, value, classes, selected ?? false, multiple, null);
        }

        public static string Checkbox(string id, object value, string classes, bool? selected, bool multiple, string addparams)
        {
            return Checkbox(id, value, classes, selected ?? false, multiple, addparams);
        }

        public static string Checkbox(string id, object value, string classes, bool selected, bool multiple, string addparams)
        {
            string str0 = id + value;
            string str3 = (string.IsNullOrEmpty(classes)) ? "" : "class=\"" + classes + "\"";
            string str4 = (selected) ? " checked" : "";
            return string.Format("<input type=\"checkbox\" id=\"{0}\" name=\"{1}\" value=\"{2}\" {3} {4} {5}/>", (multiple) ? str0 : id, id, Convert.ToString(value), str3, str4, addparams);
        }

        public static string Button(string type, string id, string onclick, string text, string classes)
        {
            string str1 = (!string.IsNullOrEmpty(classes)) ? classes : "";
            return String.Format("<button type=\"{0}\" id=\"{1}\" name=\"{1}\" onclick=\"{2}\" {3}>{4}</button>", type, id, onclick, str1, text);
        }

        public static string Radio(string name, object value, bool selected)
        {
            string str1 = (selected) ? " checked" : "";
            return string.Format("<input type=\"radio\" id=\"{0}{1}\" name=\"{0}\" value=\"{1}\" {2} />", name, Convert.ToString(value), str1);
        }

        public static string Radio(string name, object value, bool selected, string label)
        {
            return Radio(name, value, selected, label, null);
        }

        public static string Radio(string name, object value, bool selected, string label, string classes)
        {
            return Radio(name, value, selected, label, classes, null);
        }

        public static string Radio(string name, object value, bool selected, string label, string classes, string labelclasses)
        {
            return Radio(name, value, selected, label, classes, labelclasses, null);
        }

        public static string Radio(string name, object value, bool selected, string label, string classes, string labelclasses, string addparams)
        {
            string str1 = (selected) ? " checked" : "";
            string str2 = string.IsNullOrEmpty(classes) ? "" : classes;
            return string.Format("<label class=\"radio {6}\" for=\"{0}{1}\"><input type=\"radio\" id=\"{0}{1}\" name=\"{0}\" value=\"{1}\" {2} class=\"{4}\" {5}/>{3}</label>", name, Convert.ToString(value), str1, label, str2, addparams, labelclasses);
        }

        public static string ListItem(string id, string classes)
        {
            return string.Format("<li id=\"{0}\" class=\"{1}\">", id, classes);
        }

        public static string ColumnHeader(string column, string name, string orderby)
        {
            string sort = "";
            if (!string.IsNullOrEmpty(orderby))
            {
                if (orderby.Contains(column)) sort = "asc";
                if (orderby.Contains(column.Replace(",", " desc,")+" desc")) sort = "desc";
            }
            return string.Format("<a href=\"javascript:orderby('{0}')\" class=\"{2}\">{1}</a>", column, name, sort);
        }

        public static string FormatDecimal(decimal dec, int digits)
        {
            double d = Convert.ToDouble(dec);
            double ip = Math.Truncate(d);
            double dp = d - ip;
            if (dp != 0) return string.Format("{0:f}", d);
            else return ip.ToString();
        }

        /// <summary>
        /// Replaces URL in text with &lt;a href="URL"&gt;URL&lt;/a&gt;
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ReplaceUrlsWithLinks(this string text)
        {
            Regex re = new Regex("(http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)", RegexOptions.IgnoreCase);
            return re.Replace(text, "<a href=\"$1\">$1</a>");
        }

        public static string Resource(string classResourceKey)
        {
            string[] keys = new string[2];
            keys = classResourceKey.Split('.');
            if (keys == null || keys.Length != 2)
                throw new ArgumentException(string.Format("{0} is not valid resource key. Provide key in \"ResourceClass.ResourceName\" format!", classResourceKey));
         
            return Resource(keys[0], keys[1]);
        }

        public static string Resource(string classKey, string resourceKey)
        {
            return Resource(classKey, resourceKey, null);
        }

        public static string Resource(string classKey, string resourceKey, string defaultValue)
        {
            var resource = HttpContext.GetGlobalResourceObject(classKey, resourceKey);
            if (resource == null)
            {
                if (defaultValue == null)
                    throw new Exception(string.Format("Resource {0}.{1} not found!", classKey, resourceKey));
                else 
                    return defaultValue;
            }
            else return resource.ToString();
        }
    }
}
